﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;
using SPThumbnailExtender.Interne;
using Microsoft.SharePoint;

namespace SPThumbnailExtender.TimerJob
{
    public class ThumbnailExtenderTimerJobWI : SPWorkItemJobDefinition
    {
        public const string WITID = "{EC519E95-36FD-4F68-A965-D38FE159792F}";
        public const string jobName = "Thumbnail extender work item timer job";
        public ThumbnailExtenderTimerJobWI()
            : base()
        {
            this.Title = jobName;
        }

        public ThumbnailExtenderTimerJobWI(SPWebApplication app)
            : base(jobName, app)
        {
            this.Title = jobName;
        }

        protected override bool ProcessWorkItem(SPContentDatabase contentDatabase, Microsoft.SharePoint.SPWorkItemCollection workItems, Microsoft.SharePoint.SPWorkItem workItem, SPJobState jobState)
        {
            try
            {
                Guid webID = workItem.WebId;
                Guid SiteID = workItem.SiteId;
                Uri FileUri = new Uri(workItem.TextPayload, UriKind.Absolute);
                if ( Helper.IsDocumentNeedUpdate(FileUri))
                {
                    LogManager.LogInfo(workItem.TextPayload);

                    ThumbnailBase thBase = ThumbnailFactory.GenerateThumbnail(new Uri(workItem.TextPayload, UriKind.Absolute));
                    if(thBase!=null)
                        thBase.GenerateThumbnails();
                }

                using (SPSite site = new SPSite(SiteID))
                {
                    using (SPWeb web = site.OpenWeb(webID))
                    {
                        workItems.SubCollection(site, web, 0, (uint)workItems.Count).DeleteWorkItem(workItem.Id);
                    }
                }
            }
            catch(Exception ex)
            {
                LogManager.LogInfo(ex);
            }
            return true;

        }
        public override Guid WorkItemType()
        {
            return new Guid(ThumbnailExtenderTimerJobWI.WITID);
        }
    }
}
